package com.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {

	private static final String path = "/byComputer";
	private static final int maxAge=60*60*24*7;
	/**
	 * @addCookie
	 * @param name
	 * @param path
	 * @param maxAge
	 * @param value
	 * @param response
	 */
	public static void addCookie(String name, String path, int maxAge,
			String value, HttpServletResponse response) {
	
		try {
			Cookie cookie = new Cookie(name,URLEncoder.encode(value,"utf-8"));
			cookie.setPath(path);
			cookie.setMaxAge(maxAge);
			response.addCookie(cookie);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @addCookie
	 * @param name
	 * @param value
	 * @param response
	 */
	public static void addCookie(String name, String value,
			HttpServletResponse response) {
		addCookie(name,path,maxAge,value,response);
	}

	/**
	 * @delete
	 * @param name
	 * @param response
	 */
	public static void delete(String name, HttpServletResponse response) {
		Cookie cookie = new Cookie(name,"");
		cookie.setMaxAge(0);		
		response.addCookie(cookie);
	}

	/**
	 * @findCookie
	 * @param name
	 * @param value
	 * @param response
	 * @return
	 */
	public static String findCookie(String name, String value,
			HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		String value1 = null;
		for(Cookie cookie : cookies){
			if(name.equals(cookie.getName())){
				value1 = cookie.getValue();
				break;
				
			}
		}
		if(value1 !=null){
			
		}
		return null;
	}

	/**
	 * 
	 * @param str
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String enCoding(String str)
			throws UnsupportedEncodingException {
		String value = URLEncoder.encode(str, "utf-8");
		return value;
	}

	/**
	 * 
	 * @param str
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String deCoding(String str)
			throws UnsupportedEncodingException {
		String value = URLDecoder.decode(str, "utf-8");
		return value;
	}

}
